﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using MS.InformationManagement.Presenter.InsertarRadicadoInterno;
using MS.InformationManagement.DAL.DocumentCenter;
using System.Web;
using MS.InformationManagement.Presenter.Support;
using MS.InformationManagement.Support;
using MS.InformationManagement.Support.Constants;
using System.Collections;
using System.Collections.Generic;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint;
using System.Linq;
using Microsoft.SharePoint.Taxonomy;
using MS.InformationManagement.Core.TransactionsResponse;


namespace MS.InformationManagement.WP.DocumentCenter.InsertarRadicadoInterno
{
    public partial class InsertarRadicadoInternoUserControl : BaseControl, IRadicadoInternoView
    {

        #region Fields

        RadicadoInternoPresenter _presenter;
        RadicadoInterno _radicadoEntity;

        #endregion

        #region Properties

        public List<Radicado> AssociatedRadicadosData { get; set; }
        public string RadicadoGenerado { get; set; }
        public ITransactionResponse OperationResponse { get; set; }
        public string SubjectExpediente
        {
            get { return txtAsuntoExpendiente.Text; }
            set
            {
                txtAsuntoExpendiente.Text = value;
                txtAsuntoExpendiente.Enabled = string.IsNullOrEmpty(SubjectExpediente);
            }
        }
        public List<string> AssociatedRadicados
        {
            get
            {
                if (Page.Request.QueryString["associtedids"] == null)
                    return null;
                else
                {
                    List<string> selectedIds = new List<string>();
                    foreach (var id in Page.Request.QueryString["associtedids"].Split(','))
                    {
                        selectedIds.Add(id);
                    }
                    return selectedIds;
                }
            }
        }
        public string AssociatedAction
        {
            get { return Page.Request.QueryString["associatedaction"]; }
        }
        public string Sender
        {
            get { return Page.Request.QueryString["sender"]; }
        }
        public string Strategy
        {
            get 
            {
                if (string.IsNullOrEmpty(Page.Request.QueryString["strategy"]))
                    return string.Empty;
                else
                    return Page.Request.QueryString["strategy"];
            }
        }
        public RadicadoInterno RadicadoEntity
        {
            get { return _radicadoEntity; }
            set{ _radicadoEntity = value; }
        }
        public int? CurrentId
        {
            get
            {
                if (string.IsNullOrEmpty(Page.Request.QueryString["ID"]))
                    return null;
                else
                    return int.Parse(Page.Request.QueryString["ID"]);
            }
        }
        public string CurrentList
        {
            get
            {
                if (string.IsNullOrEmpty(Page.Request["ListId"]))
                    return null;
                else
                    return SPContext.Current.Web.Lists[new Guid(Page.Request["ListId"])].Title;
            }
        }

        #endregion

        #region Form Events

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                _presenter = new RadicadoInternoPresenter(this);
                if (IsPostBack) return;
                _presenter.HandleLoad();
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }

        }

        protected void Action_Save(object sender, EventArgs e)
        {
            try
            {
                if (Page.IsValid)
                {
                    selectedUsersValidation();
                    if (radProperties.Files.Count == 0)
                        throw new Exception(ExceptionConstants.ERROR_ARCHIVO_NULO);
                    getRadicado();
                    if (!CurrentId.HasValue)
                        _presenter.HandleSave();
                    else
                        _presenter.HandleUpdate();
                }
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        protected override void OnInit(EventArgs e)
        {
            try
            {
                base.OnInit(e);

                Page.RegisterAjaxLoaderPlugin();
                btnGuardar.AddLoader();                

                txtTitulo.Required(ExceptionConstants.ERROR_CAMPO_NULO, "ValBtnAddRadicado", AjaxControlToolkit.ValidatorCalloutPosition.BottomRight);
                txtTitulo.RegularExpression(RegularExpresions.EXP_ALFANUMERIC, ExceptionConstants.ERROR_INVALID_CHARACTERS, AjaxControlToolkit.ValidatorCalloutPosition.BottomRight);
                txtObservacion.Required(ExceptionConstants.ERROR_CAMPO_NULO, "ValBtnAddRadicado", AjaxControlToolkit.ValidatorCalloutPosition.BottomRight);
                radProperties.ShowOnlyFilesTab = true;
                radProperties.OnError += new InformationManagement.Controls.ErrorHandler(radProperties_OnError);
                ImbBtnSearch.OpenWindowSearchRadicado("/sites/docs/_layouts/MS.InformationManagement.WP/SearchSender.aspx?source=interno", "SearchRadicadoDialogClose");
                if (!string.IsNullOrEmpty(Sender))
                {
                    divSender.Visible = true;
                    lblSender.Text = "Informado por " + Sender;
                }

                if(AssociatedAction == "new")
                    txtAsuntoExpendiente.Required(ExceptionConstants.ERROR_EXPEDIENTE_ASUNTO, "ValBtnAddRadicado", AjaxControlToolkit.ValidatorCalloutPosition.BottomRight);

            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        protected void radProperties_OnError(object sender, Exception e)
        {
            HandleError(e);
        }

        protected void Action_Cancel(object sender, EventArgs e)
        {
            string isDlg = Request.QueryString.Get("IsDlg");
            if (!string.IsNullOrEmpty(isDlg) && isDlg.Equals("1")) { this.CloseWindow(); }
            else { this.GoCurrentUserHome(); }
        }

        #endregion

        #region Private Methods

        private void selectedUsersValidation()
        {

            foreach (var dest in PeopleEditorDestinatario.Accounts)
            {
                if (!PeopleHelper.IsSiteUser(dest.ToString()))
                    throw new Exception(string.Format(ExceptionConstants.ERROR_USUARIO_INEXISTENTE,dest.ToString().Split('\\')[1]));
                if (PeopleEditorDestinatario.Accounts.Contains(SPContext.Current.Web.CurrentUser.LoginName)) {
                    throw new Exception(ExceptionConstants.ERROR_ASIGNAR_USUARIO_RADICADOR);
                }
            }
        
        }

        private void getRadicado()
        {
            _radicadoEntity = new RadicadoInterno();
            _radicadoEntity.Name = txtTitulo.Text;
            _radicadoEntity.Description = txtTitulo.Text;
            _radicadoEntity.Asunto = txtObservacion.Text;
            _radicadoEntity.IDSubSeccion = trdSel.SelectedSubSection.HasValue ? trdSel.SelectedSubSection : 0;
            _radicadoEntity.IDTRD = trdSel.SelectedSubSerie.HasValue ? trdSel.SelectedSubSerie : 0;
            _radicadoEntity.AttachedFiles = radProperties.Files;
            _radicadoEntity.SelectedDestinatario = PeopleHelper.GetUsersFromPeopleEditor(PeopleEditorDestinatario);
            _radicadoEntity.Radicador = SPContext.Current.Web.CurrentUser.LoginName;
            _radicadoEntity.Id = CurrentId;                               
        }

        #endregion

        #region Implemented Methods

        public void RadicadoUpdated()
        {
            HandleSuccess(GlobalConstants.SUCCESS_UPDATE_RADICADO, null);
        }

        public void Show()
        {
            radProperties.ShowOnlyFilesTab = false;
            txtTitulo.Text = RadicadoEntity.Titulo;
            txtObservacion.Text = RadicadoEntity.Asunto;
            PeopleEditorDestinatario.UpdateEntities(PeopleHelper.GetSelectedPeople(RadicadoEntity.DestinatarioId, PeopleEditorDestinatario));
            trdSel.SelectedSubSerie = int.Parse(RadicadoEntity.IDTRD.Value.ToString());
            trdSel.SelectedSubSection = int.Parse(RadicadoEntity.IDSubSeccion.ToString());
            trdSel.SetInitialValues();
            radProperties.Files = RadicadoEntity.AttachedFiles;
            radProperties.Logs = RadicadoEntity.LogEntries;
            divSender.Visible = true;
            lblSender.Text = "Radicado '" + RadicadoEntity.NoRadicado + "' " + lblSender.Text;
            txtTitulo.Enabled = false;
            ShowForEdit();
        }

        public void RadicadoGenerated()
        {
            this.ShowAlertMessageAndRedirect(OperationResponse.ResponseMessage, ListHelper.CurrentUserLibraryUrl);
        }

        public void DisableControls()
        {
            txtTitulo.Enabled = false;
            txtObservacion.Enabled = false;
            PeopleEditorDestinatario.Enabled = false;
            trdSel.Enable = false;
            btnGuardar.Visible = false;
            radProperties.Enable = false;
            divSender.Visible = false;
        }

        public void LoadForAnexo()
        {
            //TRD Selection

            trdSel.SelectedSubSerie = int.Parse(AssociatedRadicadosData[0].IDTRD.Value.ToString());
            trdSel.SelectedSubSection = int.Parse(AssociatedRadicadosData[0].IDSubSeccion.ToString());
            trdSel.SelectedTipoDocumentalID = int.Parse(AssociatedRadicadosData[0].Document_Documental_Type_ID.ToString());
            trdSel.DisableTRDExceptDocumentalType = true;
            divAsuntoExpediente.Visible = true;
            //txtAsuntoExpendiente.Required(ExceptionConstants.ERROR_EXPEDIENTE_ASUNTO, "ValBtnAddRadicado", AjaxControlToolkit.ValidatorCalloutPosition.BottomRight);
            divSender.Visible = true;
            lblSender.Text = string.Format(GlobalConstants.MESSAGE_RADICADO_ASOCIATION, AssociatedRadicados[0]);

        }

        public void ShowForEdit()
        {
            this.DisableControls();
            if (radProperties.Files == null || radProperties.Files.Count == 0)
            {
                radProperties.Enable = true;
                btnGuardar.Visible = true;
            }
        }

        #endregion

    }
}
